package com.ychug.gateway.system;

import com.google.code.kaptcha.Constants;
import com.ychug.common.base.ResultAjaxHash;
import com.ychug.framework.service.SysLoginService;
import com.ychug.framework.util.ServletUtils;
import com.ychug.framework.web.base.BaseController;
import com.ychug.service.system.entity.SysUserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录验证
 * 
 * @author dds
 */
@Controller
public class SysLoginController extends BaseController {


    @Autowired
    private SysLoginService sysLoginService;

    /**
     * 跳转到登录页面
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response){

        return "modules/sys/login";
    }

    /**
     * 管理登录
     * @param username
     * @param password
     * @param validateCode
     * @param rememberMe
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public ResultAjaxHash ajaxLogin(String username, String password,String validateCode , Boolean rememberMe)
    {
        System.out.println("进入登录方法中："+username+" "+password +" "+ validateCode + " " +rememberMe );
        try
        {
            //校验验证码
            String code = (String) ServletUtils.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
            if(code == null || !code.equals(validateCode)){
                String msg = "验证码错误或者不一致！请检查！";
                return error(msg);
            }
            SysUserEntity sysUserEntity =  sysLoginService.login(username,password,validateCode);
           if(sysUserEntity != null ){
               ServletUtils.getSession().setAttribute("user",sysUserEntity);
               return success();
           }else{
               String msg = "用户或密码错误";
               return error(msg);
           }
        }
        catch (Exception e)
        {
            String msg = "用户或密码错误";
            return error(msg);
        }
    }

    /**
     * 跳转到登录页面
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response){
        ServletUtils.getSession().removeAttribute("user");
        return "modules/sys/login";
    }


}
